package org.spring.boot.sample.hystrix.command;

import rx.Observable;
import rx.Subscriber;
import rx.schedulers.Schedulers;

import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixObservableCommand;

/**
 * 前者的run()是由新创建的线程执行；后者的construct()是由调用程序线程执行
 */
public class HystrixCommandObservable extends HystrixObservableCommand<String> {

	private String name;
	public HystrixCommandObservable(String name){
		super(HystrixCommandGroupKey.Factory.asKey("MyHystrixGroup-B"));
		this.name = name;
	}

	@Override
	protected Observable<String> construct() {
		return Observable.create(new Observable.OnSubscribe<String>() {
			@Override
			public void call(Subscriber<? super String> observer) {
				if (!observer.isUnsubscribed()) {
					//observer.onError(new RuntimeException("Observable执行异常")); // 当抛出异常后，后面的程序就不会执行了
                    observer.onNext("Hello");
                    observer.onNext(name + "!");
                    System.out.println("complete before------" + " thread:" + Thread.currentThread().getName());
                    observer.onCompleted();
                    System.out.println("complete after------" + " thread:" + Thread.currentThread().getName());
                    observer.onNext(name + "not execute!"); // 不会执行
                }
			}
		}).subscribeOn(Schedulers.io());
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}
